<template>
  <div class="img"   @click="changeImg(index)" :class="{active:detail.isClick}">
    <template v-if="!detail.isEdit">
      <img :src="detail.imgUrl" alt="" model="aspectFit">
      <p style="padding:10rpx 8rpx;box-sizing:border-box;text-align: left;word-break:keep-all;text-overflow: ellipsis;overflow: hidden;font-size: 28rpx">{{detail.description}}</p>
    </template>
    <template v-if="detail.isEdit">
      <ul class="weui-uploader__files"  v-if="detail.imgUrl">

        <li class="weui-uploader__file weui-uploader__file_status"  @click="handleImagePreview('',index)"  >
          <img :src="detail.imgUrl" alt="" style="width: 100%;max-height: 100%">
          <van-icon name="close" color="red" @click="remove(index)" size="50rpx" style="position: absolute;bottom:408rpx;right:-16rpx;background: #fff;border-radius: 50%;"/>
        </li>
      </ul>
      <div class="weui-uploader__input-box" style="width: 100%;height: 450rpx;" v-if="!detail.imgUrl" @click="upload">
        <p style="position: absolute;bottom:108rpx;left:0;right: 0;text-align: center"><span style="color: rgba(0,0,0,0.5);font-size: 40rpx">上传图片</span></p>
<!--        <input id="uploaderInput"  style="width: 100%;" class="weui-uploader__input" type="file" accept="image/*" multiple="">-->
      </div>
      <van-field
        style="font-size: 28rpx"
        :value="detail.description"
        placeholder="请输入标题"
        border="false"
       @change="onChange"
      />
<!--      <input type="text" style="height: 70rpx;"   v-model.lazy="description" @change="inputFun">-->
    </template>
    <div style="margin-top:10rpx;display: flex;justify-content: center;align-items: center">
<!--      <van-button size="small" style="margin-right: 30rpx;" ></van-button>-->
      <van-button icon="edit" size="small" type="primary" @click="updateItem" v-if="!detail.isEdit" style="margin-right: 30rpx;">编辑</van-button>
      <van-button size="small" type="default" @click="outSet" v-else  style="margin-right: 30rpx;">取消</van-button>
      <van-button size="small" type="info" @click="submitFun" v-if="detail.isEdit&&detail.imgUrl" :disabled="!detail.isEdit">提交</van-button>
        <van-button size="small" type="danger" @click="delFun()"  v-if="!detail.isEdit">删除</van-button>
    </div>
    <van-dialog id="van-dialog" />
  </div>
</template>

<script>
    import * as host from "../utils/api"
    import Dialog from '../../static/vant-weapp/dist/dialog/dialog'
    export default {
        name: "createBrannerBox",
        props:['detail','index',"isEdit",'img'],
        data(){
            return {
                description: '',
                images: [],
              isFocus:false,
              img:""
            }
        },
      onReady(){
        this.img=this.detail.imgUrl;

      },
        methods:{
            delFun(){
                if(this.detail.id){
                    this.delItem();
                }

            },
          onChange(val){
              this.detail.description=val.mp.detail

          },
          outSet(){
            //   console.log(this.img)
            // this.detail.imgUrl=this.img;
            // this.detail.isEdit=false;
            // this.$forceUpdate()
           this.$emit('changeDom')
            // this.submitFun()
          },
            submitFun () {
                let cartId = wx.getStorageSync('cartId'),
                 userId = wx.getStorageSync('userId'),
                    that = this;
               // console.log(this.getEditData)
               //  if( this.detail.imgUrl.indexOf('https')==-1){//删除
               //
               //  }else{

                if( this.detail.imgUrl.indexOf('https')!=-1){
                    if (!this.detail.id) {
                        this.$http.request({
                            method: 'post',
                            url: '/api/banner/add',
                            body: {
                                cardId: cartId,
                                description: this.detail.description,
                                imgUrl: this.detail.imgUrl,
                                defaultImg:this.detail.defaultImg,
                              userId:userId
                            }
                        }).then((data) => {
                            if (data.code == 200) {
                                wx.showToast({
                                    title: '上传成功!',
                                    icon: 'success',
                                    duration: 2000,
                                    success: () => {
                                        that.images = []
                                        // that.description = ''
                                        this.detail.isEdit=false;
                                        this.$emit('changeDom')
                                    }
                                })
                            }
                        })
                    } else {
                        this.$http.request({
                            method: 'post',
                            url: '/api/banner/update',
                            body: {
                                cardId: cartId,
                                description: this.detail.description,
                                imgUrl: this.detail.imgUrl,
                                defaultImg:this.detail.defaultImg,
                                id: this.detail.id,
                              userId:userId
                            }
                        }).then((data) => {
                            if (data.code == 200) {
                                wx.showToast({
                                    title: '修改成功!',
                                    icon: 'success',
                                    duration: 2000,
                                    success: () => {
                                        that.images = [];
                                        setTimeout(()=>{
                                          this.$emit('changeDom')
                                        },1000)
                                        // that.description = ''

                                        // that.isEdit = false
                                    }
                                })
                            }
                        })
                    }
                }
            },
            delItem () {
                let that = this;

                    if(this.detail.id){
                        this.$http.request({
                            method: 'get',
                            url: '/api/banner/delete',
                            body: {
                                bannerId: this.detail.id
                            }
                        }).then((data) => {
                            if (data.code == 200) {

                                wx.showToast({
                                    title: '提交成功!',
                                    icon: 'success',
                                    duration: 2000,
                                    success: () => {
                                        this.$emit('changeDom')
                                        // that.getBanner()
                                    }
                                })
                            } else {
                                wx.showToast({
                                    title: `${data.message}`,
                                    icon: 'none',
                                    duration: 2000

                                })
                            }
                        })
                    }else{
                        wx.showToast({
                            title: `无法删除` ,
                            icon: 'none',
                            duration: 2000
                        })
                    }
                    // on confirm


            },
            updateItem(){
              // this.detail.imgUrl="";
                this.detail.isEdit=true;
                this.isFocus=true;
            },
            inputFun(val){
          //    console.log(val)
            //  console.log(this.detail.description)
            //     this.$emit('getDetail',this.detail)
            },
            handleImagePreview (img, index) { // 预览图片
                const idx = index
                const images = this.images
              //  console.log(images)
                wx.previewImage({
                    current: images[idx], // 当前预览的图片
                    urls: images // 所有要预览的图片
                })
            },
            upload (e) {
                var that = this
                let i = 0
                let upLength // 图片数组长度
                let imgFilePaths
                wx.chooseImage({
                    count: 1, // 默认9
                    sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图，默认二者都有
                    sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机，默认二者都有
                    success: function (res) {
                        // console.log(res)
                        // that.images.push(res.tempFilePaths[0])
                        // // that. urlTobase64(res.tempFilePaths[0])
                        // let len = that.files.concat(res.tempFilePaths);
                        imgFilePaths = res.tempFilePaths
                        upLength = imgFilePaths.length
                        // if(len.length > max){
                        //   that.$mptoast('图片最多只能选择' + max);
                        //   return false;
                        // }
                        /**
                         * 上传完成后把文件上传到服务器
                         */
                        wx.showLoading({
                            title: '上传中...'
                        })
                        that.upLoad(imgFilePaths, i, upLength)
                    }
                })
            },
            upLoad (imgPath, i, upLength) {
                let that = this
                let token = wx.getStorageSync('Authorization')
                // 上传文件
                wx.uploadFile({
                    url: `${host.host}/api/qiniu/upload`,
                    filePath: imgPath[i],
                    name: 'file',
                    header: {
                        'Content-Type': 'multipart/form-data',
                        'Authorization': `Bearer ${token}`
                    },

                    success: function (res) {
                     //   console.log(res.data)
                        // that.images.push( JSON.parse(res.data).data)
                        that.detail.imgUrl= JSON.parse(res.data).data
                        that.$emit('getDetail',that.detail)
                        that.$forceUpdate()
                        wx.showToast({
                            title: '上传成功!',
                            icon: 'success',
                            duration: 2000

                        })

                        // 返回选定照片的本地文件路径列表，tempFilePath可以作为img标签的src属性显示图片
                        // that.files = that.files.concat(imgPath[i]);        //合并图片显示数组
                        // let imgData = JSON.parse(res.data);
                        // that.upImg.push(imgData.data);
                    },
                    fail: function (res) {
                      //  console.log(res)
                        wx.hideLoading()
                        wx.showModal({
                            title: '错误提示',
                            content: '上传图片失败',
                            showCancel: false,
                            success: function (res) { }
                        })
                    }

                })
            },
            remove (inex) {
               this.detail.imgUrl="";
            },
            changeImg(index){
               this.$emit('getIndex',index)
                // this.detail.forEach((a,i)=>{
                //     a.isClick=false;
                //     if(i==index){
                //         a.isClick=true;
                //     }
                // })
                // this.editData=this.detailListCopy[index];
                // this.$forceUpdate()
                // console.log(this.detailList)
            },
        }
    }
</script>
<style>
  .img .van-cell{
    padding:2rpx 8rpx;
  }
  .img ._input{
    width:100%;
    /*height: 70rpx;*/
  }
  .img .weui-uploader__file_status:before{
    background-color:transparent ;
  }
  .img .weui-uploader__files{
    width: 100%;
    height:450rpx;
  }
  .img .weui-uploader__files .weui-uploader__file{
   width: 100%;
    height: 450rpx;

  }
</style>
<style scoped>
  .bannerImg{
    display: flex;
    justify-content: space-between;
    flex-wrap: wrap;
    box-sizing: border-box;
    padding:5%;
  }
  .img{
    width: 45%;
    text-align: center;
    margin-bottom: 40rpx;
    box-sizing: border-box;
    padding-bottom: 10rpx;
    box-shadow: 1px 1px 2px #999;
    border:1px solid transparent;
  }
  .img.active{
    border-color: rgb(61,176,243);
    border-radius: 10rpx;
  }
  .img img{
    max-width: 100%;
    height:450rpx;
  }

</style>
